package com.auto.autoapp.widgets

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.core.content.withStyledAttributes
import com.auto.autoapp.R
import com.auto.autoapp.databinding.ViewSectionBinding

class SectionView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private val binding: ViewSectionBinding =
        ViewSectionBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        attrs?.let {
            context.withStyledAttributes(it, R.styleable.SectionView) {
                val text = getString(R.styleable.SectionView_sectionText)
                val startRes = getResourceId(R.styleable.SectionView_startIcon, 0)
                val endRes = getResourceId(R.styleable.SectionView_endIcon, 0)
                if (text != null) setText(text)
                if (startRes != 0) setStartIcon(startRes)
                if (endRes != 0) setEndIcon(endRes)
            }
        }
    }

    fun setText(text: CharSequence?) {
        binding.tvContent.text = text ?: ""
    }

    fun setStartIcon(drawable: Drawable?) {
        binding.ivStart.setImageDrawable(drawable)
        binding.ivStart.visibility = if (drawable == null) View.GONE else View.VISIBLE
    }

    fun setStartIcon(resId: Int) {
        if (resId == 0) {
            setStartIcon(null)
        } else {
            binding.ivStart.setImageResource(resId)
            binding.ivStart.visibility = View.VISIBLE
        }
    }

    fun setEndIcon(drawable: Drawable?) {
        binding.ivEnd.setImageDrawable(drawable)
        binding.ivEnd.visibility = if (drawable == null) View.GONE else View.VISIBLE
    }

    fun setEndIcon(resId: Int) {
        if (resId == 0) {
            setEndIcon(null)
        } else {
            binding.ivEnd.setImageResource(resId)
            binding.ivEnd.visibility = View.VISIBLE
        }
    }

    fun setOnStartIconClickListener(listener: ((View) -> Unit)?) {
        binding.ivStart.setOnClickListener { v -> listener?.invoke(v) }
    }

    fun setOnEndIconClickListener(listener: ((View) -> Unit)?) {
        binding.ivEnd.setOnClickListener { v -> listener?.invoke(v) }
    }

    fun setStartIconVisible(visible: Boolean) {
        binding.ivStart.visibility = if (visible) View.VISIBLE else View.GONE
    }

    fun setEndIconVisible(visible: Boolean) {
        binding.ivEnd.visibility = if (visible) View.VISIBLE else View.GONE
    }
}